import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Row, Col, Card, Form, Select, Icon, Button, DatePicker } from 'antd';
import RecommendRecordTable from '../../../components/Huishuaka/Acount/RecommendRecord';
import PageHeaderLayout from '../../../layouts/PageHeaderLayout';

import styles from './RecommendRecord.less';

const getValue = obj => Object.keys(obj).map(key => obj[key]).join(',');
const FormItem = Form.Item;
const { Option } = Select;
const smartTypes = RecommendRecordTable.smartTypes;

@connect(({ recommendRecord, loading }) => ({
  recommendRecord,
  loading: loading.models.recommendRecord,
}))
@Form.create()
export default class RecommendRecordList extends PureComponent {
  state = {
    expandForm: false,
    formValues: {},
  };
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'recommendRecord/init',
    });
    dispatch({
      type: 'recommendRecord/fetch',
    });
  }
  toggleForm = () => {
    this.setState({
      expandForm: !this.state.expandForm,
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'recommendRecord/fetch',
      payload: params,
    });
  }

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'recommendRecord/fetch',
      payload: {},
    });
  }

  toggleForm = () => {
    this.setState({
      expandForm: !this.state.expandForm,
    });
  }

  createRow = () => {
    const { recommendRecord: { dynmicColumns } } = this.props;
    const { getFieldDecorator } = this.props.form;
    const nodes = [];
    const rowLength = Math.ceil(dynmicColumns.length / 3);
    const createCol = (index) => {
      const cols = [];
      // eslint-disable-next-line max-len
      const colNums = dynmicColumns.length - (index * 3) >= 3 ? 3 : dynmicColumns.length - (index * 3);
      for (let i = 0; i < colNums; i++) {
        const col = dynmicColumns[(index * 3) + i];
        let separator = '\r\n';
        if (col.smart_option.indexOf(separator) === -1) {
          separator = '\n';
        }
        const datas = col.smart_option.split(separator);
        cols.push(
          <Col md={8} sm={24}>
            <FormItem label={col.smart_type}>
              {getFieldDecorator(`record_recommend_id_${col.smart_id}`)(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  {
                    datas.map(data => <Option value={data}>{data}</Option>)
                  }
                </Select>
              )}
            </FormItem>
          </Col>
        );
      }
      return cols;
    };
    for (let i = 0; i < rowLength; i++) {
      nodes.push(<Row gutter={{ md: 8, lg: 24, xl: 48 }}>{createCol(i)}</Row>);
    }
    return nodes;
  }

  handleSearch = (e) => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'recommendRecord/fetch',
        payload: values,
      });
    });
  }

  renderSimpleForm() {
    const { getFieldDecorator } = this.props.form;
    const { recommendRecord: { dynmicChannels } } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="开始日">
              {getFieldDecorator('begin_date')(
                <DatePicker id="begin_date" style={{ width: '100%' }} placeholder="请输入开始日" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="结束日">
              {getFieldDecorator('end_date')(
                <DatePicker id="end_date" style={{width: '100%'}} placeholder="请输入结束日" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="来源渠道">
              {getFieldDecorator('record_appMgr')(
                <Select id="record_appMgr" placeholder="请选择" style={{width: '100%'}}>
                  {
                    dynmicChannels.map(channel =>
                      <Option value={channel.channelId}>{channel.channelName}</Option>
                    )
                  }
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="基本信息状态">
              {getFieldDecorator('record_baseIdent')(
                <Select id="record_baseIdent" placeholder="请选择" style={{width: '100%'}}>
                  <Option value={0}>未认证</Option>
                  <Option value={1}>认证</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="身份证">
              {getFieldDecorator('record_idIdent')(
                <Select id="record_idIdent" placeholder="请选择" style={{width: '100%'}}>
                  <Option value={0}>未认证</Option>
                  <Option value={1}>认证</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="推荐类别">
              {getFieldDecorator('record_type')(
                <Select id="record_type" placeholder="请选择" style={{width: '100%'}}>
                  {
                    smartTypes.map(type =>
                      <Option value={type.value}>{type.text}</Option>
                    )
                  }
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <div style={{ overflow: 'hidden' }}>
          <span style={{ float: 'right', marginBottom: 24 }}>
            <Button type="primary" htmlType="submit">查询</Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
            <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                收起 <Icon type="up" />
            </a>
          </span>
        </div>
      </Form>
    );
  }

  renderAdvancedForm() {
    const { getFieldDecorator } = this.props.form;
    const { recommendRecord: { dynmicChannels } } = this.props;

    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="开始日">
              {getFieldDecorator('begin_date')(
                <DatePicker style={{ width: '100%' }} placeholder="请输入开始日" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="结束日">
              {getFieldDecorator('end_date')(
                <DatePicker style={{ width: '100%' }} placeholder="请输入结束日" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="来源渠道">
              {getFieldDecorator('record_appMgr')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  {
                    dynmicChannels.map(channel =>
                      <Option value={channel.channelId}>{channel.channelName}</Option>
                    )
                  }
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="基本信息状态">
              {getFieldDecorator('record_baseIdent')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value={0}>未认证</Option>
                  <Option value={1}>认证</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="身份证">
              {getFieldDecorator('record_idIdent')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value={0}>未认证</Option>
                  <Option value={1}>认证</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="推荐类别">
              {getFieldDecorator('record_type')(
                <Select id="record_type" placeholder="请选择" style={{width: '100%'}}>
                  {
                    smartTypes.map(type =>
                      <Option value={type.value}>{type.text}</Option>
                    )
                  }
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        {this.createRow()}
        <div style={{ overflow: 'hidden' }}>
          <span style={{ float: 'right', marginBottom: 24 }}>
            <Button type="primary" htmlType="submit">查询</Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
            <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                收起 <Icon type="up" />
            </a>
          </span>
        </div>
      </Form>
    );
  }

  renderForm() {
    return this.state.expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  render() {
    const { recommendRecord: { data, dynmicColumns, dynmicChannels }, loading } = this.props;

    return (
      <PageHeaderLayout title="智能推荐记录统计">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>
              {this.renderForm()}
            </div>
            <RecommendRecordTable
              loading={loading}
              data={data}
              dynmicColumns={dynmicColumns}
              dynmicChannels={dynmicChannels}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
      </PageHeaderLayout>
    );
  }
}
